# 预计：生成两个气泡重叠的照片
import argparse
import math
import array
import cv2
import numpy as np
import scipy
import os
import random
from matplotlib import pyplot as plt
from scipy.signal import savgol_filter
import ellipsefit_ltl

def gen_overlop_ideal(pic_num):
    i=0
    height = 256
    width = 256
    while (i<pic_num):
# 随机选取两张图片，并进行二值化
        img1 = np.zeros((height, width), np.uint8)
        img2 = np.zeros((height, width), np.uint8)
        img_overlop = np.zeros((height, width), np.uint8)  # 创建空画布

        ellipse1_center_x = width/2
        ellipse1_center_y = height/2
        ellipse1_2a = width/2+np.random.uniform(-width/3,width/3)
        ellipse1_2b = ellipse1_2a * np.random.uniform(0.9,1.1)
        ellipse1_angle = np.random.uniform(-180,180)
        area1 = math.pi * ellipse1_2a/2 * ellipse1_2b/2 # 椭圆面积计算
        cv2.ellipse(img1, [[ellipse1_center_x, ellipse1_center_y], [ellipse1_2a, ellipse1_2b], ellipse1_angle],(255, 255, 255), -1)
        cv2.ellipse(img_overlop, [[ellipse1_center_x, ellipse1_center_y], [ellipse1_2a, ellipse1_2b], ellipse1_angle],(255, 255, 255), -1)

        # 第二个椭圆
        ellipse2_angle = np.random.uniform(-180,180) # 随机角度
        ellipse2_2a = width / 2 + np.random.uniform(-width / 3, width / 3)
        ellipse2_2b = ellipse2_2a * np.random.uniform(0.9,1.1)
        # 为第二个椭圆生成一个随机的中心点
        theta = np.random.uniform(-180,180)*(math.pi/180.0)
        half_diag = pow(pow(height/2,2)+pow(width/2,2),0.5) # 随机距离，范围1/2对角线长
        a=random.choice([-1,1])
        distance = abs(np.random.uniform(a*half_diag/3, a*half_diag))
        # distance = np.random.uniform(-half_diag,half_diag)
        ellipse2_center_y = (height/2)+distance*math.cos(theta)
        ellipse2_center_x = (width/2)+distance*math.sin(theta)
        cv2.ellipse(img2, [[ellipse2_center_x,ellipse2_center_y],[ellipse2_2a,ellipse2_2b],ellipse2_angle], (255, 255, 255), -1)
        cv2.ellipse(img_overlop, [[ellipse2_center_x,ellipse2_center_y],[ellipse2_2a,ellipse2_2b],ellipse2_angle], (255, 255, 255), -1)
        # cv2.imshow('img_overlop', img_overlop)

        A = img1 * img2
        overlop_pixel = np.sum(A >= 1)  # 计算叠加两张图片时，重叠的像素数。A是两张图片对应位置相乘，非零即重叠。条件为大于等于1
        overlop_ratio = overlop_pixel/area1
        if overlop_ratio>1:
                overlop_ratio = 1
        cv2.imwrite('gen_overlop_ideal0831\\%d.jpg'%i,img_overlop)
        file = open('gen_overlop_ideal0831\\%d.txt'%i,'w')
        file.write(str(area1)+'\n'+str(overlop_ratio)) # 第一行为中间气泡的面积真值，第二行为重叠比例
        file.close()

        i+=1
        print(i)
        # # return img_overlop, area1

gen_overlop_ideal(1)